#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

import subprocess
import os
import os.path
import socket
import time
import urllib

from cloudcfg.lib.cmd import Cmd

__version__="1.0"

class cmd_xen(Cmd):
	__FILE__ = 'xenversion.x86_64'
	__URL__ = 'http://14.63.252.33/'
	
	def __init__(self, logger):
		Cmd.__init__(self,logger)

	def checkHypervisorVersion(self):
		"""
		get binary for checking
		"""
		url = '%s%s' % (self.__URL__, self.__FILE__)
		target = '/tmp/%s' % self.__FILE__
		
		try:
			urllib.urlretrieve(url, target)
			cmd_string = ['chmod','700',target]
			(out, err) = self.run(cmd_string)
			cmd_string = [target]
			(out,err) = self.run(cmd_string)
			if out:
				item = out.split(" ")
				self.logger.debug("Xen Hypervisor:%s" % out)
				return item[0]
		except:
			return 0

	def queryRPM(self, name, major):
		cmd_string = ['rpm','-qa','|','grep', name]
		try:
			(out, err) = self.run(cmd_string)
			#pattern : xe-guest-utilities-5.6.100 
			pattern = '%s-%s' % (name, major)
			result = re.findall(pattern, out)
			self.logger.debug("query RPM:%s" % out)
			if len(result) > 0:
				return (True, out)
			else:
				return (False, err)
		except:
			return (False, 'Failed to execute cmd')
		
	def installXentools(self, paks, major, minor):
		"""
		install xentools packages
		@param paks : ['xe-guest-utilities', 'xe-guest-utilities-xenstore']
		@param major : 6.0.2
		@param minor : 756
		"""
		arch = 'x86_64'
		
		for pak in paks:
			package = "%s-%s-%s.%s.rpm" % (pak, major, minor, arch)
			self.logger.debug("Install package : %s" % package)
			url = "%s%s" % (self.__URL__, package)
			target = '/tmp/%s' % package
			urllib.urlretrieve(url, target)
			cmd_string = ['rpm','-Uvh',target]
			self.run(cmd_string)
			
	
	def updateXentools(self):
		"""
		update xentools based on current hypervisor version

		hypervisor 3.4 : xenserver 5.6
		                 (xe-guest-utilities-5.6 xxx.rpm, xe-guest-utilities-xenstore-xxx.rpm)
		hypervisor 4.1 : xenserver 6.0.2
		                 (
		"""
		# hypervisor : ([packages],major, minor)
		# package name : xe-guest-utilities-<major>-<minor>.<arch>.rpm
		
		update_dic = {
			'3.4' : (['xe-guest-utilities','xe-guest-utilities-xenstore'],'5.6.100','651'),
			'4.1' : (['xe-guest-utilities','xe-guest-utilities-xenstore'],'6.0.2', '756'),
			}

		hypervisor = self.checkHypervisorVersion()

		#try current installed version
		need_update = False
		if update_dic.has_key(hypervisor) == True:
			(paks, major, minor) = update_dic[hypervisor]
			if self.queryRPM(paks[0], major) == True:
				self.logger.debug("Correct xentools")
				return True
			else:
				self.installXentools(paks, major, minor)
				return True
		return false
	
		#if not match
		#update xentools
		
		
		


